package com.grj.community.all.intercepter;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTHeader;
import cn.hutool.jwt.JWTUtil;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 14505
 */
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token").replaceAll("Bearer ", "");
        if(StringUtils.isEmpty(token)) {
            throw new Exception("token不存在");
        }
        if(!JWTUtil.verify(token, "1234".getBytes())) {
            throw new Exception("token无效");
        }
        final JWT jwt = JWTUtil.parseToken(token);
        jwt.getHeader(JWTHeader.TYPE);
        response.setHeader("uid",jwt.getPayload("uid").toString());
        return true;
    }
}
